package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import utils.ItemsHelper;
import entities.Item;

/**
 * Servlet implementation class Search
 */
@WebServlet("/Search")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String SEARCH_TEXT = "searchText";
	private static final String ITEMS = "items";

	
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json");
		response.setStatus(200);
		
		List<Item> itemsList = ItemsHelper.search(
				request.getParameter(SEARCH_TEXT), 
				ServletsUtil.getStartFrom(request,response),
				ServletsUtil.getPageNumber(request, response)
				);
		ItemsHelper.isUsersItem(itemsList,ServletsUtil.getUserID(request));
			ObjectMapper mapper = new ObjectMapper();
			PrintWriter writer = response.getWriter();
			writer.write(
						"{\"" + ITEMS +"\":" + mapper.writeValueAsString(itemsList) + "}"					
						);
			writer.flush();
	}
	

}
